const axios = require('axios')
const express = require("express");
const route = express.Router();
const {clientId, clientSecrets} = require('../github')
const {formatResponseData} = require("../utils/response");
const {addGithub, findGithub} = require('../services/githubServices')
const {sign} = require("../utils/jwt");
/**
 * 获取当前的client_id
 */

route.get('/clientId', (req, res) => {
    res.send(formatResponseData(200, clientId, '操作成功'))
})

/**
 * 根据code 获取 token
 */
route.post('/getToken', async (req, res) => {
    // 拿到 code
    const code = req.body?.code;
    if (!code) {
        res.send(formatResponseData(400, null, '参数传递错误'))
        return
    }
    // 根据拿到的 code 组装 post 请求的参数
    const body = {
        code: req.body.code,
        client_secret: clientSecrets,
        client_id: clientId,
    }
    // 获取用户的 access_token
    const {data} = await axios.post('https://github.com/login/oauth/access_token', body)
    const token = new URLSearchParams(data).get('access_token');
    // 拿到token之后 获取用户信息
    const {data: info} = await axios.get('https://api.github.com/user', {
        headers: {
            'Authorization': `Bearer ${token}`,
        }
    })

    const githubInfo = {
        id: info.id,
        name: info.login,
        avatar_url: info.avatar_url,
        originalData: info
    }

    // 先根据当前的id进行判断 看当前用户信息是否存在
    let findData = await findGithub({id: githubInfo.id});
    if (!findData || findData.length === 0) {
        // 如果不存在 就进行保存
        findData = await addGithub(githubInfo)
    }

    const userToken = sign({type: 'github', id: findData[0]._id}, '1d');
    res.send(formatResponseData(200, userToken, '登录成功'))
})

module.exports = route;